﻿using RabbitMQ.Client;
using System.Diagnostics;
using System.Text;

namespace RabbitMQDemo.Producer
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start the producer");

            var connFactory = new ConnectionFactory
            {
                HostName = "106.53.127.56",
                Port = 5672,
                UserName = "rabbitmqdemo",
                Password = "rabbitmqdemo@test",
                VirtualHost = "rabbitmqdemo"
            };
            using (var conn = connFactory.CreateConnection())
            {
                using (var channel = conn.CreateModel())
                {
                    var queueName = "helloworld_producerack_batchconfirm";
                    channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
                    channel.ConfirmSelect();

                    #region 批量Confirm模式
                    //while (true)
                    //{
                    //    for (int i = 0; i < 3; i++)
                    //    {
                    //        Console.WriteLine("消息内容(exit退出):");
                    //        var message = Console.ReadLine();
                    //        if (message.Trim().ToLower() == "exit")
                    //        {
                    //            break;
                    //        }

                    //        var body = Encoding.UTF8.GetBytes(message);
                    //        channel.BasicPublish(exchange: "", routingKey: queueName, basicProperties: null, body: body);
                    //        Console.WriteLine("消息内容发送完毕:" + message);
                    //    }

                    //    Console.WriteLine(channel.WaitForConfirms() ? "所有消息内容发送完毕" : "存在消息发送失败");
                    //}
                    #endregion

                    #region 批量Confirm模式 Foreach
                    var stopwatch = new Stopwatch();
                    stopwatch.Start();
                    for (int i = 0; i < 5000; i++)
                    {
                        var message = "第" + (i + 1) + "条消息";
                        var body = Encoding.UTF8.GetBytes(message);
                        channel.BasicPublish(exchange: "", routingKey: queueName, basicProperties: null, body: body);
                        Console.WriteLine("消息内容发送完毕:" + message);
                    };
                    Console.WriteLine(channel.WaitForConfirms(new TimeSpan(0, 0, 1)) ? "所有消息内容发送完毕" : "存在消息发送失败");
                    stopwatch.Stop();
                    Console.WriteLine($"BatchConfirm耗时：{stopwatch.ElapsedMilliseconds}");
                    #endregion
                }
            }
        }
    }
}